//
//  JZMainViewController.swift
//  SwiftWeibo
//
//  Created by Stone on 16/12/2.
//  Copyright © 2016年 Stone. All rights reserved.
//

import UIKit

//主控制器
class JZMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpChildControllers()
        setUpCompseButton()
    }
    
    
    
    //MARK: - 中间button监听方法
    func composeButtonAction() {
       let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
    
    
    
    
    
    
    //MARK: - 私有控件
     lazy var composeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add_highlighted", backgroundImageName:"tabbar_compose_button")

}

//extension 类似于OC中的分类,  在swift中还可以用来切分代码块
//可以把相近功能的函数,放在一个extention中
//便于代码维护
//注意, 和oc的分类一样,extention中不能定义属性
//MARK: - 设置界面

extension JZMainViewController {
    
    //设置中间按钮
    func setUpCompseButton() {
        tabBar.addSubview(composeButton)
        
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        //按钮缩进的宽度, 让他变大一点, 则可以处理一个容错点
        let w = tabBar.bounds.width / count - 1
        
        //CGRectInset  正数向内缩进, 负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        composeButton.addTarget(self, action: #selector(composeButtonAction), for: .touchUpInside)
    }
    
    //设置所有子控制器
    func setUpChildControllers() {
    
        //获取沙盒路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        //如果没有data,则从本地bundle中取
        if data == nil {
            let path = Bundle.main.path(forResource: "main.JSON", ofType: nil)
            data = NSData(contentsOfFile: path!)
            
        }
        //到这里,data肯定有一个数据, 进行序列化操作
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : Any]] else {
                return
        }
        
        
        //先创建控制器
    
//        let array: [[String : Any]] = [
//        ["clsName": "JZHomeViewController", "title":"首页", "imageName":"home", "visitorInfo": ["imageName":"", "message":"关注一些人,回这里看看有什么惊喜"]],
//        ["clsName": "JZMessageViewController", "title":"消息", "imageName":"message_center", "visitorInfo": ["imageName":"visitordiscover_image_message", "message":"登录后,最新、最热微博尽在掌握,不再会与事实潮流擦肩而过"]],
//        ["clsName": "UIViewController"],
//        ["clsName": "JZDiscoverViewController", "title":"发现", "imageName":"discover", "visitorInfo": ["imageName":"visitordiscover_image_message", "message":"登录后, 别人评论你的微博, 发给你的小新, 都会在这里收到通知"]],
//        ["clsName": "JZProdfileViewController", "title":"我", "imageName":"profile", "visitorInfo": ["imageName":"visitordiscover_image_profile", "message":"登录后,你的微博、相册、个人资料会显示在这,展示给别人"]],
//        ]
//        
//        //测试数据格式是否正确,转换成plist数据更加直观
////        (array as NSArray).write(toFile: "/Users/stone/Desktop/demo.plist", atomically: true)
//        //数组 -> json 序列化
//        let data = try!JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//
//        (data as NSData).write(toFile: "/Users/stone/Desktop/demo.json", atomically: true)
        
        var arrayM = [UIViewController]()
        for dict in array! {
            
            arrayM.append(controller(dict: dict))
            
        }
        
      viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - parameter dict: 信息字典[clsName, title, iamgeName, visitorInfo]
    ///
    /// - returns: 子控制器
    private func controller(dict: [String: Any]) -> UIViewController {
        //取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? JZBaseViewController.Type,
            let visitorInfoDict = dict["visitorInfo"] as? [String: String] else {
                return UIViewController()
        }
        
        //创建视图控制器
        //将clsName转换成cls
        let vc = cls.init()
        vc.title = title
        vc.visitorInfoDict = visitorInfoDict
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //设置tabBar的标题字体
        vc.tabBarItem.setTitleTextAttributes(
            [NSForegroundColorAttributeName:UIColor.orange],
            for: .highlighted)
        //系统默认的是12号
        vc.tabBarItem.setTitleTextAttributes(
            [NSFontAttributeName: UIFont.systemFont(ofSize: 12)],
            for: .normal)
        let nav = JZNavgationController(rootViewController: vc)
        
        return nav
    }
}
